#include <iostream>
#include <unistd.h>
#include <thread>
#include <mutex>
#include <condition_variable>
class H2o
{
public:
    H2o()
        : _Ocount(0),
          _Hcount(0)
    {
    }
    void H()
    {
        while (true)
        {
            sleep(1);
            std::unique_lock<std::mutex> lock(_mutex);
            _Hcv.wait(lock, [this]
                      { return _Hcount == 0; });
            std::cout << "H " << "H ";
            _Hcount += 2;
            _Ocv.notify_one();
        }
    }
    void O()
    {
        while (true)
        {
            sleep(1);
            std::unique_lock<std::mutex> lock(_mutex);
            _Ocv.wait(lock, [this]
                      { return _Hcount == 2; });
            std::cout << "O" << std::endl;
            _Ocount++;
            if (_Hcount == 2 && _Ocount == 1)
            {
                _Hcount = 0;
                _Ocount = 0;
                std::cout << "生成了一个水" << std::endl;
            }
            _Hcv.notify_one();
        }
    }

private:
    std::mutex _mutex;
    std::condition_variable _Hcv, _Ocv;
    int _Ocount;
    int _Hcount;
};
int main()
{
    H2o h2o;
    std::thread h1(&H2o::H, &h2o);
    std::thread h2(&H2o::O, &h2o);
    h1.join();
    h2.join();
    return 0;
}